package com.ytclub.wx.handler;

import com.ytclub.wx.constants.WxConstant;
import com.ytclub.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户文本消息处理类
 *
 * @author: HuangQi
 * @date: Created in 20:43 2024/3/25
 * @description: 用户文本消息处理
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler {

    /**
     * 关键字
     */
    private static final String KEY_WORD = "验证码";

    /**
     * 登录前缀
     */
    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取用户文本消息类型
     *
     * @return 用户文本消息类型
     */
    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    /**
     * 处理用户文本消息
     *
     * @return 处理结果
     */
    @Override
    public String dealMsg(Map<String, String> msgMap) {
        log.info(WxConstant.RECIVET_TEXT_LOG_INFO);
        // 判断用户发送的是什么
        String content = msgMap.get(WxConstant.CONTENT);
        if (!KEY_WORD.equals(content)) {
            return WxConstant.UNKNOWN_RECEIVE_TEXT_WORD_KEY;
        }

        // 构建回复信息(验证码)
        String fromUserName = msgMap.get(WxConstant.FROMUSERNAME);
        String toUserName = msgMap.get(WxConstant.TOUSERNAME);
        Random random = new Random();
        int loginCode = random.nextInt(1000);

        // 将验证码存入redis
        String loginKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(loginCode));
        redisUtil.setNx(loginKey, fromUserName, 5L, TimeUnit.MINUTES);

        String numContent = "您当前的验证码是：" + loginCode + "！ 5分钟内有效";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";
        return replyContent;
    }
}
